package com.start.common.tools;

import com.start.common.entity.StartDicData;
import com.start.common.enums.StartBaseEnum;
import com.start.common.std.StartDesc;
import com.start.common.exceptions.StartBusException;
import com.start.common.std.StartDisabled;

import java.util.ArrayList;
import java.util.List;

public class StartEnumTools {
    public static List<StartDicData> getEnumDic(Class clazz) {
        return getEnumDic(clazz, new ArrayList<>());
    }

    public static List<StartDicData> getEnumDic(Class clazz, List<String> disabledValues) {
        if (!clazz.isEnum()) throw new StartBusException("class:" + clazz.getName() + " is not enum");
        Object[] enumConstants = clazz.getEnumConstants();
        List<StartDicData> list = new ArrayList<>();
        if (disabledValues == null) {
            disabledValues = new ArrayList<>();
        }

        if (!StartBaseEnum.class.isAssignableFrom(clazz)) {
            for (Object obj : enumConstants) {
                String val = obj.toString();
                list.add(new StartDicData(val, val, disabledValues.contains(val)));
            }
            return list;
        }
        for (Object obj : enumConstants) {
            StartBaseEnum baseEnum = (StartBaseEnum) obj;
            StartDicData startDicData = new StartDicData(baseEnum.getLabel(), baseEnum.getValue());
            if (StartDesc.class.isAssignableFrom(clazz)) {
                StartDesc desc = (StartDesc) obj;
                startDicData.setDesc(desc.getDesc());
            }
            if (!disabledValues.isEmpty() && disabledValues.contains(baseEnum.getValue())) {
                startDicData.setDisabled(true);
            } else if (StartDisabled.class.isAssignableFrom(clazz)) {
                StartDisabled disabled = (StartDisabled) obj;
                startDicData.setDisabled(disabled.getDisabled());
            }
            list.add(startDicData);
        }
        return list;
    }

    /**
     * 根据value 获取枚举类型
     *
     * @param enumClazz 枚举类型
     * @param value     枚举值
     * @param <T>
     * @return
     */
    public static <T extends StartBaseEnum> T findEnumByValue(Class<?> enumClazz, Object value) {
        if (value == null) {
            return null;
        }
        StartBaseEnum[] enumConstants = (StartBaseEnum[]) enumClazz.getEnumConstants();
        for (StartBaseEnum e : enumConstants) {
            if (e.getValue().equals(value)) return (T) e;
        }
        return null;
    }


}
